package com.jml.config;

import com.jml.redis.MyRedisObjectSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisTwoConfig {
	@Bean("redisTwo")
	public RedisTemplate<String,Object> getRedisTemplate(
			@Value("${spring.redis-two.host}")String hostName,
			@Value("${spring.redis-two.password}")String password,
			@Value("${spring.redis-two.port}")int port,
			@Value("${spring.redis-two.database}")int database,
			@Value("${spring.redis-two.pool.max-active}")int maxActive,
			@Value("${spring.redis-two.pool.max-idle}")int maxIdea,
			@Value("${spring.redis-two.pool.min-idle}")int minIdea,
			@Value("${spring.redis-two.pool.max-wait}")long maxWait){
		RedisConnectionFactory redisConnectionFactory = getRedisConnectionFactory(hostName,
				password, port,database, maxActive, maxIdea, minIdea, maxWait);
		RedisTemplate<String,Object> redisTemplate=new RedisTemplate<String,Object>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		//设置key的序列化类型
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		//设置value的序列化类型
		redisTemplate.setValueSerializer(new MyRedisObjectSerializer());
		return redisTemplate;
	}

	public RedisConnectionFactory getRedisConnectionFactory(String hostName,String password,int port,int database,
			int maxActive,int maxIdea,int minIdea,long maxWait){
		JedisConnectionFactory jedisConnectionFactory=new JedisConnectionFactory();
		jedisConnectionFactory.setHostName(hostName);
		jedisConnectionFactory.setPassword(password);
		jedisConnectionFactory.setPort(port);
		jedisConnectionFactory.setDatabase(database);
		//--------------------------------------------
		JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(maxActive);
		jedisPoolConfig.setMaxIdle(maxIdea);
		jedisPoolConfig.setMinIdle(minIdea);
		jedisPoolConfig.setMaxWaitMillis(maxWait);
		//--------------------------------------------
		jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
		// 初始化连接池配置
		jedisConnectionFactory.afterPropertiesSet();
		return jedisConnectionFactory;
	}
}
